﻿
Imports osi.root.connector

Public Class comparable_type
    Implements IComparable(Of comparable_type), IComparable(Of Type), IComparable

    Private Shared ReadOnly cmp As Func(Of Type, Type, Int32)
    Private ReadOnly t As Type

    Shared Sub New()
        If envs.mono Then
            cmp = Function(x As Type, y As Type) As Int32
                      Return x.AssemblyQualifiedName().CompareTo(y.AssemblyQualifiedName())
                  End Function
        Else
            cmp = Function(x As Type, y As Type) As Int32
                      Return x.GUID().CompareTo(y.GUID())
                  End Function
        End If
    End Sub

    Public Sub New(ByVal i As Type)
        Me.t = i
    End Sub

    Public Sub New(ByVal i As comparable_type)
        Me.new(+i)
    End Sub

    Public Shared Function compare_type(ByVal i As Type, ByVal j As Type) As Int32
        Dim r As Int32 = 0
        r = object_compare(i, j)
        If r = object_compare_undetermined Then
            Return cmp(i, j)
        Else
            Return r
        End If
    End Function

    Public Shared Operator +(ByVal this As comparable_type) As Type
        If this Is Nothing Then
            Return Nothing
        Else
            Return this.t
        End If
    End Operator

    Public Shared Widening Operator CType(ByVal this As comparable_type) As Type
        Return +this
    End Operator

    Public Shared Widening Operator CType(ByVal this As Type) As comparable_type
        Return New comparable_type(this)
    End Operator

    Public Function CompareTo(ByVal other As comparable_type) As Int32 _
                             Implements IComparable(Of comparable_type).CompareTo
        Return compare_type(+Me, +other)
    End Function

    Public Function CompareTo(ByVal obj As Object) As Int32 Implements IComparable.CompareTo
        Dim a As comparable_type = Nothing
        If cast(Of comparable_type)(obj, a) Then
            Return CompareTo(a)
        Else
            Return CompareTo(cast(Of Type)(obj, False))
        End If
    End Function

    Public Function CompareTo(ByVal other As Type) As Int32 Implements IComparable(Of Type).CompareTo
        Return compare_type(+Me, other)
    End Function
End Class
